package com.cpp.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import weibo4j.model.Paging;
import weibo4j.model.Status;
import weibo4j.model.StatusWapper;
import weibo4j.model.User;
import weibo4j.model.UserWapper;
import weibo4j.model.WeiboException;
import weibo4j.org.json.JSONArray;
import weibo4j.org.json.JSONException;
import weibo4j.org.json.JSONObject;

import com.cpp.util.SinaWeiboUtil;

/**
 * Servlet implementation class Login_sina
 */
public class ShowWeibo_sina extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowWeibo_sina() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		response.setContentType("text/html"); 
//	    request.setCharacterEncoding("UTF-8"); 
//	    response.setCharacterEncoding("UTF-8"); 

		JSONObject jsonObject = new JSONObject();
		PrintWriter pw = response.getWriter();
		if(request.getSession().getAttribute("token") == null){
			//需要登录
			try {				
				String login_url = new SinaWeiboUtil().getLoginUrl();
				jsonObject.put("success", "1");//未登录
				jsonObject.put("login_url", login_url);//登陆地址
				pw.write(jsonObject.toString());
				pw.close();
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			String token =(String) request.getSession().getAttribute("token");
			String screenName = "";
			User user = null;
			if(request.getParameter("screenName") != null && !(request.getParameter("screenName").equals(""))){
				screenName = request.getParameter("screenName");				
				try {
					user =  new SinaWeiboUtil().showUserByScreenName(screenName);
				} catch (WeiboException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{				
				//user = (User)request.getSession().getAttribute("user");
			}
			
			int pageNum = 1;
			if(request.getParameter("pageNum") != null){
				pageNum = Integer.parseInt(request.getParameter("pageNum"));
			}
			Paging page = new Paging();
			page.setCount(20);
			page.setPage(pageNum);
			StatusWapper statusWapper = null;
			try {
				JSONArray array = new JSONArray();
				jsonObject.put("success", "0");
				if(!screenName.equals("")){
					statusWapper = new SinaWeiboUtil().getUserTimelineByName(screenName,page);
				}else{
					statusWapper = new SinaWeiboUtil(token).getFriendsTimeline(page);
				}				
				jsonObject.put("previousCursor", statusWapper.getPreviousCursor());
				jsonObject.put("nextCursor", statusWapper.getNextCursor());
				jsonObject.put("totalNumber", statusWapper.getTotalNumber());
				
				List<Status> status = statusWapper.getStatuses();
				for(Status s : status){					
					array.put(getMap(s));
				}
				
				jsonObject.put("weibo", array);
				pw.write(jsonObject.toString());
				
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}
		pw.close();
		
	}
	
	private Map getMap(Status s){
		Map<String,Object> map = new HashMap<String,Object>();	
		String t = s.getText();
		map.put("uid", s.getUser().getId());
		map.put("text", getText(t));
		map.put("name", s.getUser().getName());
		map.put("verified", s.getUser().isVerified());
		map.put("source", s.getSource().getName());
		map.put("repostsCount", s.getRepostsCount());
		map.put("commentsCount", s.getCommentsCount());
		map.put("profileImageUrl", s.getUser().getProfileImageUrl());
		
		if("".equals(s.getThumbnailPic())){
			map.put("thumbnailpic", "");//thumbnailPic
			map.put("originalPic", "");
		}else{
			map.put("thumbnailpic", s.getThumbnailPic());//thumbnailPic
			map.put("originalPic", s.getOriginalPic());//原始图片
		}
		
		if(s.getRetweetedStatus() != null){
			//Map temp_map = new HashMap();
			map.put("retweetedstatus", getMap(s.getRetweetedStatus()));
			//getJson(s.getRetweetedStatus(),temp_map);
		}
		else{
			map.put("retweetedstatus", null);
		}
		return map;
		//array.put(s);
	}
	
	public static String getText(String text){
		//System.out.println(text);
		String temp_text = text;
		char[] ts = text.toCharArray();
		
		for(int i = 0;i < ts.length;i++){
			char t = ts[i];
			//判断@人名
			if('@' == t){
				int num = i+1;
				boolean bl = true;
				String http_temp = "";
				while(bl){
					if(num >= ts.length){
						break;
					}
					char th = ts[num];
					if(Character.getType(th) == Character.OTHER_LETTER) {   //汉字
						http_temp+=th;			                 
			        }
			        else if(Character.isDigit(th)) {//数字
			        	http_temp+=th;				            
			        }
			        else if(Character.isLetter(th)) {//字母
			        	http_temp+=th;				            
			        }
			        else if(th == '_') {//下划线 _
			        	http_temp+=th;				            
			        }
			        else{
			        	break;
			        }					
					num++;
				}				
				temp_text = temp_text.replaceAll("@"+http_temp, "<a href=\"\">"+"@"+http_temp+"</a>");
			}
			
			//判断短链
			if('h' == t){				
				if(ts.length-i <= 12){
					break;
				}
				String t_http_temp = text.substring(i,i+12);
				if(t_http_temp.equals("http://t.cn/")){
					boolean bl = true;
					int num = i+12;
					String http_temp = "";
					while(bl){
						if(num >= ts.length){
							break;
						}
						char th = ts[num];
						if(Character.getType(th) == Character.OTHER_LETTER) {   //汉字
							break;				                 
				        }
				        else if(Character.isDigit(th)) {//数字
				        	http_temp+=th;				            
				        }				        
				        else if(Character.isLetter(th)) {//字母
				        	http_temp+=th;				            
				        }				        
				        else {
				        	break;//其它字符				             
				        }
						num++;
					}
					String rep = "http://t.cn/"+http_temp;
					temp_text = temp_text.replaceAll("http://t.cn/"+http_temp, "<a href=\""+rep+"\">"+rep+"</a>");
					//System.out.println("http://t.cn/"+http_temp);
				}
			}			
		}
		return temp_text;
	}
	
	public static void main(String[] args){
		String ss = "我只想说这是我见过http://t.cn/iidjnheir最有魄力，最有性格，最http://www.baidu.com有内涵的女生！！真的十分欣赏，佩服！！！！值得我们学习！《非你莫属》 李铭筱，十几家公司争来争去，人才啊http://t.cn/zOms52N";
		
		System.out.println(getText(ss));
	}
	
	

}
